package com.inspectortime.webapp.payment;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PaymentUtils {
	
	private PaymentUtils() {}
	
	private static int LAST_SEQUENCE_NUMBER_SUFFIX = 1;
	private static long LAST_TIMESTAMP;

	/**
	 * Generates a unique invoice number. Also generates timestamp and sequence
	 * number (which are the parts from which invoice number is formed). Format
	 * is [datetime] [ip octet] [unique serial#]
	 * 
	 * @return a String array consisting of timestamp, sequence number, and
	 *         invoice number
	 */
	public static synchronized String[] generateInvoiceNumber() {

		long timestamp = System.currentTimeMillis() / 1000;

		// Ensure we create a unique sequence number
		int sequenceNumberPrefix = retrieveLastOctetOfLocalIp();
		int sequenceNumberSuffix;
		if (timestamp != LAST_TIMESTAMP) {
			LAST_SEQUENCE_NUMBER_SUFFIX = 0;
		}
		sequenceNumberSuffix = ++LAST_SEQUENCE_NUMBER_SUFFIX;
		String seqNumber = String.valueOf(sequenceNumberPrefix)
				+ String.valueOf(sequenceNumberSuffix);
		LAST_TIMESTAMP = timestamp;

		// Create date component (to second) based on timestamp
		Date myDate = new Date(timestamp * 1000);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String invoiceNum = dateFormat.format(myDate) + seqNumber;
		String[] returnValues = new String[3];
		returnValues[0] = String.valueOf(timestamp);
		returnValues[1] = seqNumber;
		returnValues[2] = invoiceNum;
		return returnValues;
	}

	private static int retrieveLastOctetOfLocalIp() {
		String ip;
		try {
			ip = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			throw new RuntimeException(
					"Could not get InetAddress.getLocalHost().getHostAddress()",
					e);
		}
		int lastDotPos = ip.lastIndexOf(".");
		String lastOctet = ip.substring(lastDotPos + 1);
		int lastOctetInt = Integer.valueOf(lastOctet);
		return lastOctetInt;
	}


}
